package com.spzx.user.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.user.controller.HttpUtils;
import com.spzx.user.service.ISmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.executor.statement.StatementUtil;
import org.springframework.stereotype.Service;

import java.awt.desktop.UserSessionEvent;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: SmsServiceImpl
 * Package: com.spzx.user.service.impl
 * Description:
 *
 * @Author ycy
 * @Create 2024/8/19 21:25
 * @Version 1.0
 */
@Slf4j
@Service
public class SmsServiceImpl implements ISmsService {
    @Override
    public void send(String phone, String templateCode, Map<String, Object> param) {
        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        String appcode = "你的appcode(自己的短信服务项)";
        Map<String,String> headers = new HashMap<>();

        headers.put("Authorization","APPCODE" + appcode);

        headers.put("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

        Map<String,String> querys = new HashMap<>();
        Map<String,String> bodys = new HashMap<>();

        StringBuffer contentBuffer = new StringBuffer();
        param.entrySet().forEach(item ->{
            contentBuffer.append(item.getKey()).append(":").append(item.getValue()).append(",");
        });
        String content = contentBuffer.substring(0,contentBuffer.length() - 1);

        bodys.put("content",content);
        bodys.put("phone_number",phone);
        bodys.put("template_id",templateCode);

        try {
            /**
             * 重要提示如下：
             * HttpUtils 从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             * 相应依赖参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             *
             */
            HttpResponse response = HttpUtils.doPost(host,path,method,headers,querys,bodys);
            //获取response的body
            String data = EntityUtils.toString(response.getEntity());

            HashMap<String,String> resultMap = JSONObject.parseObject(data,HashMap.class);

            String status = resultMap.get("status");
            if (!"OK".equals(status)){
                String reason = resultMap.get("reason");
                log.error("短信发送失败：status = " + status + "reason = " + reason);
                throw new ServiceException("短信发送失败");
            }


        }catch (Exception e){
            throw new ServiceException("短信发送失败");
        }

    }
}
